package com.yc.sole.common.filter;

import cn.hutool.core.collection.CollUtil;
import com.yc.sole.framework.web.SecurityAuthenticator;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.PathMatcher;

import java.io.IOException;
import java.util.Collection;

/**
 * 白名单过滤器
 *
 * @author yizuomin
 * @date 2022/11/29 16:58
 **/
@Slf4j
@RequiredArgsConstructor
@WebFilter(urlPatterns = "/api/**")
@Order(1)
@Component
public class WhiteListFilter implements Filter {

    private final SecurityAuthenticator securityAuthenticator;
    private final PathMatcher pathMatcher;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info("白名单过滤器初始化成功！");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestURI = request.getRequestURI();
        //接口白名单
        Collection<String> whiteList = securityAuthenticator.getWhiteList();
        boolean matchWhiteList = false;
        if (CollUtil.isNotEmpty(whiteList)) {
            for (String path : whiteList) {
                if (pathMatcher.match(path, requestURI)) {
                    matchWhiteList = true;
                    break;
                }
            }
        }
        if (matchWhiteList) {
            chain.doFilter(servletRequest, servletResponse);
        } else {
            servletRequest.setAttribute("executeTokenFilter", true);
            chain.doFilter(servletRequest, servletResponse);
        }
    }
}
